package cyan.gf.core;

import cyan.gf.control.MessageBox;
import cyan.gf.util.PropReader;
import cyan.gf.util.StagePool;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by cyan on 2017/2/15.
 * Email:qsyan@vip.qq.com
 */
public class Initializer extends Application {

  private static int DEF_WIDTH = 1050;
  private static int DEF_HEIGHT = 700;

  private static Logger logger = LogManager.getLogger(Initializer.class);


  @Override
  public void start(Stage primaryStage) throws Exception {
    PropReader.load("/config/config.properties");
    Parent root = FXMLLoader.load(getClass().getResource("/fxml/initializer.fxml"));
    Scene primaryScene = new Scene(root, DEF_WIDTH, DEF_HEIGHT);
    primaryStage.setTitle(String.format("%s (%s)", PropReader.getString("app.title"), PropReader.getString("app.version")));
    primaryStage.setScene(primaryScene);
    primaryStage.getIcons().addAll(new Image("/images/logo.png"));
    primaryStage.show();
    StagePool.put("main", primaryStage);
    initTemplete();
  }

  private void initTemplete() {
    PropReader.load("/config/config.properties");
    String templeteDir = System.getProperty("user.home") + PropReader.getString("app.templeteDir");
    String[] templetes = PropReader.getString("app.templetes").split(",");
    String tempExt = ".ftl";
    File propDir = new File(templeteDir);
    File tempFile;
    if (!propDir.exists()) {
      if (!propDir.mkdirs()) {
        MessageBox.error("main", "templete file load error.");
      }
    }
    for (String tempName : templetes) {
      tempFile = new File(templeteDir + tempName + tempExt);
      if (!tempFile.exists()) {
        copyTempete("/templete/" + tempName + tempExt, templeteDir + tempName + tempExt);
      }
    }
    logger.debug("templete dir:" + templeteDir);
  }

  private void copyTempete(String resourceDir, String destDir) {
    InputStream in = null;
    FileOutputStream out = null;
    try {
      int byteread;
      in = getClass().getResourceAsStream(resourceDir);
      File destFile = new File(destDir);
      out = new FileOutputStream(destFile);
      byte[] buffer = new byte[1024];
      while ((byteread = in.read(buffer)) != -1) {
        out.write(buffer, 0, byteread);
      }
    } catch (IOException e) {
      logger.error(e);
    } finally {
      try {
        assert in != null;
        in.close();
        assert out != null;
        out.close();
      } catch (IOException e) {
        logger.error(e);
      }
    }
  }

  public static void main(String[] args) {
    launch();
  }

}
